package com.ws.demo.second;

import com.alibaba.fastjson.JSONObject;
import com.ws.demo.second.server.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.websocket.Session;
import java.util.Map;

@Controller
@RequestMapping("ws-demo")
public class DemoController {

    @Autowired
    private WebSocketServer webSocketServer;

    @GetMapping("users/{from}/{to}")
    public ModelAndView userPage(@PathVariable("from") String from,
                                 @PathVariable("to") String to,
                                 ModelAndView modelAndView) {
        modelAndView.addObject("to", to);
        modelAndView.addObject("from", from);
        modelAndView.setViewName("users");

        return modelAndView;
    }

    @GetMapping("push/{message}")
    @ResponseBody
    public void push(@PathVariable("message") String message) {
        Map<String, Session> sessionMap = WebSocketServer.sessionMap;
        if (!sessionMap.isEmpty()) {

            sessionMap.forEach((key, value) -> {
                JSONObject json = new JSONObject();
                json.put("from", "server");
                json.put("to", key);
                json.put("message", message);
                webSocketServer.sendMsg(value, json.toJSONString());
            });
        }
    }
}
